var ExperienceLevelController = require("ExperienceLevelController");
var PlayerController = require("PlayerController");

cc.Class({
    extends: cc.Component,

    properties: {
        expValue: 0,

        movingToPlayer: false,
        moveSpeed: 0,

        timeBetweenChecks: 0.2,
        checkCounter: 0,
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    start () {
        this.playerNodePosition = PlayerController.instance.playerNode.getComponent(cc.RigidBody).getWorldPosition();
    },

    update (dt) {
        this.playerNodePosition = PlayerController.instance.playerNode.getComponent(cc.RigidBody).getWorldPosition();
        if (this.movingToPlayer == true) {
            this.node.getComponent(cc.RigidBody).linearVelocity = this.playerNodePosition.sub(this.node.getComponent(cc.RigidBody).getWorldPosition()).normalize()
            .mulSelf(this.moveSpeed);
        } else {
            this.checkCounter -= dt;
            if (this.checkCounter <= 0) {
                this.checkCounter = this.timeBetweenChecks;

                if (cc.v2(this.node.getComponent(cc.RigidBody).getWorldPosition()).sub(this.playerNodePosition).mag() < PlayerController.instance.pickUpRange) {
                    this.movingToPlayer = true;
                    this.moveSpeed *= 2;
                }
            }
        }
    },

    onBeginContact(contact, selfCollider, otherCollider) {
        if (otherCollider.node.group == 'Player') {
            ExperienceLevelController.instance.getExp(this.expValue);

            this.node.destroy();
            
        }

    },
});
